package com.platform.common.security.interceptor.auth;

import com.platform.common.security.config.AuthConfigProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * 拦截器配置类
 */
@Slf4j
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Resource
    private AuthInterceptor authInterceptor;

    @Resource
    private RepeatSubmitInterceptor repeatSubmitInterceptor;

    @Resource
    private AuthConfigProperties authConfigProperties;
    @Resource
    private ParamResultFilter requestBodyFilter;
    /** 不需要拦截地址 */
    public static final String[] excludeUrls = {
            "/platApp/info/**", // 获取应用详情
            "/platApp/getApp2ApiList", // 获取所有应用和接口操作权限列表
            "/logininfor",
            "/user/info/**",
            "/user/register",
            "/error",
            // -- swagger ui
            "/",
            "/configuration/ui",
            "/configuration/security",
            "/webjars/**"
    };
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册TestInterceptor拦截器
        InterceptorRegistration registration = registry.addInterceptor(authInterceptor);
        // 所有路径都被拦截
        registration.addPathPatterns("/**");
        // 添加不拦截路径
        List<String> whitesList = authConfigProperties.getWhites();
        Collections.addAll(whitesList, excludeUrls);
        registration.excludePathPatterns(whitesList);

        registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**");
    }

    /**
     * 通过FilterRegistrationBean实例注册 过滤器
     *  解决拦截器中从流中获取完 post 请求中的 body 参数，controller 层无法再次获取的问题
     *  需要枚举 配置
     * @return
     */
    @Bean
    public FilterRegistrationBean setLogServiceFilter() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();

        registrationBean.setFilter(requestBodyFilter);
        registrationBean.setName("interceptor filter body params");
        registrationBean.addUrlPatterns("/*");
        registrationBean.setOrder(1);
        return registrationBean;
    }


}
